import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter, Link } from 'react-router-dom';
import { Flex, Button, Progress, WhiteSpace, Table, Tools, List, Modal } from 'weaver-mobile';
import { SearchAdvanced } from 'weaver-mobile-page';
import { renderNoData } from '../../util';
import BackTop from '../../public/back-to-top';
import RoutModal from './RoutModal';

const getLabel = Tools.getLabel;
const store = [
  'resultStore',
  'votingStore',
]

@withRouter
@inject(...store)
@observer
export default class Result extends Component {
  static defaultProps = {
    prefixCls: 'voting-result'
  }

  constructor(props) {
    super(props);
    this.path = props.location.pathname;
    this.modal = '';
    this.state = {
      id: props.match.params.id || '',
      isActive: 0
    }
  }

  componentWillMount() {
    const { resultStore: { getRes, getpartSituation, setStoreState, inital } } = this.props;
    setStoreState({path: this.path, votingid: this.state.id});
    inital();
    getRes();
    getpartSituation();
  }

  componentDidMount() {
    setTimeout(()=>{
      let context = document.getElementsByClassName('value');
      if (context) {
        for(let i of context) {
          i.addEventListener('click', this.openAimLink)
        }
      }
    },800)
  }

  componentWillUnmount() {
    typeof this.modal.close === 'function' && this.modal.close();
  }

  openAimLink = (e) => {
    const { history, location: {pathname}} = this.props;
    let questionid = e.target.getAttribute('data_questionid');
    let optionid = e.target.getAttribute('data_optionid');
    history.push(`${pathname}/optionView/${questionid}/${optionid}`);
  }

  // 统计报表每一行的数据
  getTableList = (datas) => {
    const { prefixCls } = this.props
    let arr = datas ? datas.map(record => {
      let contain = this.getContainTable(record.otherView, record);
      return (
        <List.Item className={`${prefixCls}-container-statistics-question`} key={record.questionid}>
          <div className='label'>{record.label}{record.labelExt}</div>
          <div className='answer'>
            <Link to={{pathname:`${this.path}/answerList/${record.questionid}`, state: {id: this.state.id}}}>{record.percent}</Link>
            {record.otherView === '1' && (
              <Link to={{pathname:`${this.path}/other/${record.questionid}`, state: {id: this.state.id}}}>{getLabel(25740, '其他')}</Link>
            )}
            {record.otherView === '3' && (
              <Link to={{pathname: `${this.path}/viewList/${record.questionid}`, state: {id: this.state.id}}}>{getLabel('33564','查看') }</Link>
            )}
          </div>
          <div className='options'>{contain}</div>
        </List.Item>
      )
    }) : [];
    return arr
  }

  onItemClick = (data) => {
    if (data.indexOf('<div')=== -1) {
      this.modal = Modal.alert(data,'',[{text: 'OK'}])
    }
  }

  getContainTable = (type, record) => {  //0-单选不含其他，1-单选含其他，2-组合，3-填空
    if (type === '2') {
      let columns = this.getContainTableColumns(record.columns, type, record);
      return (
        <Table className='com' columns={columns} dataSource={record.dataSource} onItemClick={this.onItemClick} rowKey='key' />
      )
    }else if (type !== '3') {
      let columns = this.getContainTableColumns(record.columns, type, record);
      return (
        <Table className='radio' columns={columns} dataSource={record.dataSource} onItemClick={this.onItemClick} autoFill={1} rowKey='key' />
      )
    } else return;
  }

  getContainTableColumns = (columns, type, record) => {
    let parentRecord = { ...record }
    let newColumns = { ...columns }
    let content = document.getElementsByClassName('am-list-content');
    let contentWidth, leftWidth, rightWidth;
    if (content) {
      contentWidth = content[0].offsetWidth;
      leftWidth = contentWidth && Math.floor(contentWidth/7);
      rightWidth = contentWidth && Math.ceil(contentWidth/3);
    }
    newColumns = columns.map(item => {
      if (item.dataReader === 'value') {
        if (type !== '2') item.width = leftWidth || 80;
        return item; 
      }
      else {
        item.render = (text, record) => {
          let percent = record.qnums === 0 ? 0 : (text / record.qnums).toFixed(4);
          percent = Math.round(percent * 10000) / 100;
          let TooltipTitle = record.qnums === 0 ? '0(0%)' : `${text}(${percent}%)`;
          let optionid = record.optionid;
          if (optionid.indexOf("_") > -1) {
            optionid = `${record.key}_${item.key.split("_")[1]}`;
          }

          if (type === '2') {
            return (
              <div className='options' key={optionid}>
                <Progress percent={percent} position='normal' />
                <span className='value' data_questionid={parentRecord.questionid} data_optionid={optionid}>{TooltipTitle}</span>
              </div>
            )
          }

          return (
            <div className='option-row' key={optionid}>
              <Progress percent={percent} position='normal' />
              <span className='value' data_questionid={parentRecord.questionid} data_optionid={optionid}>{TooltipTitle}</span>
            </div>
          )
        }
        if (type !== '2') item.width = rightWidth || 100;
        return item
      }
    })
    return newColumns
  }

  getPerson = (type) => {
    if (type === 'join') {
      this.setState({ isActive: 0 });
      this.props.history.push({pathname: `${this.path}/resJoin`, state: {id: this.state.id}})
    } else if (type === 'nojoin') {
      this.setState({ isActive: 1 });
      this.props.history.push({pathname: `${this.path}/resnotJoin`, state: {id: this.state.id}})
    }
  }

  openLink = (e, href) => {
    e.preventDefault();
    window.openLink(href);
  }

  exportExcel = (e) => {
    this.openLink(e, `/voting/ObtainExcelData.jsp?votingid=${this.state.id}`)
  }

  urgent = () => {
    const { history, title, resultStore: { urgentStore, votingid } } = this.props;
    const { getUrgentNum } = urgentStore;
    getUrgentNum({votingid}).then(res => {
        if (res.num * 1) {
            history.push({pathname: `${this.path}/urgent`, state: { title }});
        } else {
            this.modal = Modal.alert(getLabel('516746','调查已全部填写，无须进行催办'), '', [
                { text: getLabel('826','确定') }
            ])
        }
    })
  }

  render() {
    const { prefixCls, resultStore, title } = this.props;
    const { statistics, report, adSearch, doResultReset, isUrgent } = resultStore;
    const { isActive } = this.state;
    const buttonGroupData = [
      { key: 'reset',
        text: getLabel(2022,"重置"),
        onClick: doResultReset
      },
      { key: 'submit',
        text: getLabel('?',"搜索"),
        onClick: () => {
          // getVotingList();
          // history.go(-1);
        },
        type: 'primary',
      }
    ];
    let percent = statistics.doSize * 100 / statistics.totalSize
    percent = Math.floor(percent * 100) / 100;
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-container`}>
          <BackTop
            visibilityHeight='200'
            modal
            target={`${prefixCls}-container-box`}
          >
            <div className={`${prefixCls}-container-box`}>
              <div className={`${prefixCls}-container-title`}>{title || ''}</div>
              <div className={`${prefixCls}-container-msg`}>
                <div className='adSearch'>
                  {/* <Link to={adSearch.path}><Icon type='filter-o' size='xs'/></Link> */}
                  <SearchAdvanced
                    store={adSearch}
                    buttonGroupData={buttonGroupData}
                  />
                </div>
                <div className='statistics'>
                  <Progress type='circle' percent={percent} showInfo circleWidth={120}>
                    <div className='num'>{statistics.totalSize}</div>
                    <div className='label'>{getLabel('505516','应参与人数')}</div>
                  </Progress>
                </div>
                <Flex>
                  <Flex.Item className={`join ${isActive === 0 && 'active'}`} onClick={() => this.getPerson('join')}>
                    <div className='number'>{statistics.doSize}</div>
                    <div className='title'><i/>{getLabel('33849','已参与')}</div>
                  </Flex.Item>
                  <Flex.Item className={`join ${isActive === 1 && 'active'}`} onClick={() => this.getPerson('nojoin')}>
                    <div className='number'>{statistics.unDoSize}</div>
                    <div className='title'><i/>{getLabel('33850','未参与')}</div>
                  </Flex.Item>
                </Flex>
              </div>
              <div className={`${prefixCls}-container-statistics-title`}>{getLabel(25177, '统计报表')}</div>
              <List className={`${prefixCls}-container-statistics`}>
                {toJS(report).length === 0 ? renderNoData() :this.getTableList(toJS(report))}
              </List>
              <WhiteSpace/>
            </div>
          </BackTop>
        </div>
        <Flex className={`${prefixCls}-btns`}>
            <Flex.Item>
                <Button type={!isUrgent ? 'primary' : ''} onClick={this.exportExcel}>{getLabel('518717','导出数据明细')}</Button>
            </Flex.Item>
            { isUrgent && (
                <Flex.Item style={{margin: 0}}>
                    <Button type='primary' onClick={this.urgent}>
                    {getLabel('500432','催办')}
                    </Button>
                </Flex.Item>
            )}
        </Flex>
        <RoutModal path={this.path}/>
      </div>
    )
  }
}